package com.chat.module.message.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.chat.module.message.domain.ChatInfoLog;
import com.comment.pojo.domain.chat.WsMessage;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.module.message.mapper.ChatInfoLogMapper;
import com.chat.module.message.service.ChatInfoLogService;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * (ChatInfoLog)表服务实现类
 *
 * @author cxy
 * @since 2024-12-16 15:42:25
 */
@Slf4j
@Service
public class ChatInfoLogServiceImpl extends ServiceImpl<ChatInfoLogMapper, ChatInfoLog> implements ChatInfoLogService {
    @Resource
    private ChatInfoLogMapper chatInfoLogMapper;

    public ChatInfoLog obtainChatInfoBy(
            int code, Set<Long> receiverUserIdList, int i
    ) {

        if (code == 1) {
            ChatInfoLog one =obtainChatInfoLogByCode1(receiverUserIdList);
            chatInfoLogObtainMessageByIds(i, one);
            return one;
        }else if (code == 2){
            Set<WsMessage> wsMessages = WsMessageService.messageGetByCode(2, 50L);
            ChatInfoLog chatInfoLog = new ChatInfoLog();
            chatInfoLog.setMessageInfo(wsMessages);
            return chatInfoLog;
        }

        return null;
    }

    private @NotNull ChatInfoLog obtainChatInfoLogByCode1(Set<Long> receiverUserIdList) {
        ChatInfoLog one = getChatInfoLog(receiverUserIdList);
        if (one == null) {
            throw new RuntimeException("未找到会话记录");
        }
        return one;
    }

    /**
     * 获取聊天记录(通过聊天频道存储的messageIds)
     *
     * @param i   返回数量
     * @param one 会话记录
     */
    private static void chatInfoLogObtainMessageByIds(int i, ChatInfoLog one) {
        one.messageInfo = new HashSet<>();
        int index = 0;
        for (Long messageId : one.messageIds) {
            index++;
            if (index < i) {
                WsMessage wsMessage = WsMessageService.messageGetById(Math.toIntExact(messageId));
                if (wsMessage != null) {
                    wsMessage.setCode(null);
                    one.messageInfo.add(wsMessage);
                }
            }
        }
    }

    public @Nullable ChatInfoLog getChatInfoLog(Set<Long> userList) {
        String jsonStr = JSONUtil.toJsonStr(userList);
        JSONObject jsonObject = chatInfoLogMapper.selectByUserIds(jsonStr);
        return jsonObject == null ? null : jsonObject.toJavaObject(ChatInfoLog.class);
    }

    public ChatInfoLog selectBy(Long playerId, int id) {
        ChatInfoLog one = chatInfoLogMapper.selectById(id);
        if (one.getUserIds().contains(playerId)) {
            chatInfoLogObtainMessageByIds(50, one);
        }
        return one;
    }
}
